JavaScript accessing form elements using document.forms[].elements[]

Posted by thecoshman on Stack Overflow See other posts from Stack Overflow or by thecoshman
Published on 2010-04-27T09:05:39Z Indexed on 2010/04/27 9:13 UTC
Read the original article Hit count: 302

Filed under:
|
|
var loc_name = document.forms['create_<?php echo(htmlspecialchars($window_ID)); ?>'].elements['location_name'];
alert(loc_name);

This just gives me the message 'undefined'

where as...

var loc_name = document.forms['create_<?php echo(htmlspecialchars($window_ID)); ?>'];
alert(loc_name);

Gives me the object form business.

Have I just got this all wrong? What is the 'proper' way to access this form element. The form element has the correct name and it has an id, the id is similar but not the same.

** HTML - as reuqested **

 <form action="javascript:void(0)" name="create_<?php echo(htmlspecialchars($window_ID)); ?>" method="GET" onsubmit="return false">
    <td>
      <input type="text" id="location_name_<?php echo($window_ID); ?>" name="location_name" value="Enter a name" onfocus="if(this.value == 'Enter a name'){this.value = ''}" onblur="if(this.value == ''){ this.value = 'Enter a name' }" />
    </td>
    <td colspan="2">
      <input type="button" name="create_location" value="Create" onclick="var pre_row_was = $('#pre_form_row_<?php echo($window_ID); ?>').innerHTML; $('#pre_form_row_<?php echo($window_ID); ?>').innerHTML = '<td colspan=\'3\'>Validating...</td>'; var loc_name = document.forms['create_<?php echo(htmlspecialchars($window_ID)); ?>'].elements['location_name']; alert(loc_name); if(loc_name.value == '') { alert('You can\'t leave the room name blank'); loc_name.focus(); loc_name.value = 'Enter a name'; $('#pre_form_row_<?php echo($window_ID); ?>').innerHTML = pre_row_was; return false; } if(loc_name.value == 'Enter a name') { alert('You must enter a room name first'); loc_name.focus(); $('#pre_form_row_<?php echo($window_ID); ?>').innerHTML = pre_row_was; return false; } $('#pre_form_row_<?php echo($window_ID); ?>').innerHTML = pre_row_was; Window_manager.new_window().load_xml('location/create.php?location_name=' + loc_name.value).display();" />
    </td>
  </form>

ugly as sin that is...

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about forms